package com.ikdong.toodle.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.ikdong.toodle.R;
import com.ikdong.toodle.service.SyncService;
import com.ikdong.toodle.util.Constant;
import com.ikdong.toodle.util.TaskTabAdapterFactory;
import com.ikdong.toodle.widget.TaskTabFragment;
import com.viewpagerindicator.TabPageIndicator;

public class TaskListActivity extends BasicActivity implements ActionBar.OnNavigationListener,OnPageChangeListener{	
	public static final String SORT_ITEM = "SORT_ITEM";
	public static final String SORT_BY = "SORT_BY";
	public static final String SORT_FOLDER = "Folder";
	public static final String SORT_DUE_DATE = "Due-Date";
	public static final String SORT_START_DATE = "Start-Date";
	public static final String SORT_STATUS = "Status";
	public static final String SORT_PRIORITY = "Priority";
	public static final String SORT_DATE_ADD = "Date Added";
	public static final String SORT_DATE_MODIFY = "Date Modified";
	public static final Long SORT_BY_NORMAL = Long.valueOf(0);
	public static final Long SORT_BY_RESERVES = Long.valueOf(1);
	private FragmentStatePagerAdapter adapter;
	private ViewPager pager;
	private TabPageIndicator indicator;
	private String sView = Constant.TASK_VIEW_TAB_MAIN;
	private int sPosition = 0;
	private SharedPreferences sp;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {  
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list);
		sp = getSharedPreferences(Constant.CONFIG_FILE, 0);
        initView();


        Bundle bundle = this.getIntent().getExtras();
        if(bundle!=null && bundle.getBoolean(Constant.PARAM_LAUNCH,false)){	
			showToast(this.getString(R.string.msg_start_syn));
	        setSupportProgressBarIndeterminateVisibility(true);
        	Intent intentService = new Intent(this,SyncService.class);
			startService(intentService);
        }
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportActionBar().setTitle("");
		
        MenuItem addItem = menu.add(this.getString(R.string.actionbar_title_add_task));
        addItem.setIcon(R.drawable.ic_action_add);
        addItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        addItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				Intent intent = new Intent(TaskListActivity.this,TaskAddActivity.class);
				intent.putExtra(TaskAddActivity.OPERATION, TaskAddActivity.OP_ADD);
				startActivityForResult(intent, 0);
				return true;
			}});
        
        MenuItem sortItem = menu.add(this.getString(R.string.actionbar_title_sort_task));
        sortItem.setIcon(R.drawable.ic_sort);
        sortItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        sortItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				showSortDialog();
				return true;
			}});
        
        return true;
    }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(TaskAddActivity.OP_ADD==resultCode || TaskAddActivity.OP_UPDATE==resultCode){
			this.initPager(sView, sPosition);
		}
	}
	
	@Override
	public void onResume(){
		super.onResume();
	}
	
	private void initView(){
		Context context = getSupportActionBar().getThemedContext();
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.task_views, R.layout.sherlock_spinner_item);
        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        getSupportActionBar().setListNavigationCallbacks(list, this);  
        
        String view = Constant.TASK_VIEW_TAB_NONE;
        int position = 0;
        Bundle bundle = this.getIntent().getExtras();
        if(bundle!=null){
        	view = bundle.getString(Constant.TASK_VIEW_CATALOG);
        	position = bundle.getInt(Constant.TASK_VIEW_TAB_POSITION);
        }
        
        this.findViewById(R.id.task_list_loading).setVisibility(View.VISIBLE);
        this.findViewById(R.id.task_list_view).setVisibility(View.GONE);
        pager = (ViewPager)findViewById(R.id.pager);
        indicator = (TabPageIndicator)findViewById(R.id.indicator);
        indicator.setOnPageChangeListener(this);
        adapter = TaskTabAdapterFactory.getTabAdapter(this, view);
        pager.setAdapter(adapter); 
        indicator.setViewPager(pager,position); 
	}
	
	private void initPager(String view, int position){
		new TabRefreshTask().execute(position);
	}

	@Override
	public void refresh(){
		initPager(sView,sPosition);
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    	Log.d(Constant.TAG, "onNavigationItemSelected");
		if(itemPosition==0){
			sView = Constant.TASK_VIEW_TAB_MAIN;
		}else if(itemPosition==1){
			sView = Constant.TASK_VIEW_TAB_FOLDER;
		}else if(itemPosition==2){
			sView = Constant.TASK_VIEW_TAB_DUEDATE;
		}else if(itemPosition==3){
			sView = Constant.TASK_VIEW_TAB_PRIORITY;
		}else if(itemPosition==4){
			sView = Constant.TASK_VIEW_TAB_STATUS;
		}else if(itemPosition==5){
			sView = Constant.TASK_VIEW_TAB_CONTEXT;
		}else if(itemPosition==6){
			sView = Constant.TASK_VIEW_TAB_GOAL;
		}
        sPosition = 0;

		this.findViewById(R.id.task_list_loading).setVisibility(View.VISIBLE);
        this.findViewById(R.id.task_list_view).setVisibility(View.GONE);
		initPager(sView,sPosition);
		return true;
	}

	@Override
	public void onPageScrollStateChanged(int state) {				
		if(state==0){
	    	Log.d(Constant.TAG, "onPageScrollStateChanged");
			TaskTabFragment framents = (TaskTabFragment) adapter.getItem(sPosition);
	    	framents.refresh();				
		}
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
	}

	@Override
	public void onPageSelected(int position) {
		sPosition = position;
	}
    
    int selectedSort = -1;
	private void showSortDialog(){	
		final String[] values = new String[]{SORT_DATE_ADD,SORT_DATE_MODIFY,SORT_FOLDER,SORT_DUE_DATE,SORT_START_DATE,SORT_STATUS,SORT_PRIORITY};
		String value = sp.getString(SORT_ITEM, SORT_DATE_ADD);
		for(int i=0; i<values.length; i++){
			if(values[i].equals(value)){
				selectedSort = i;
				break;
			}
		}
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(TaskListActivity.this);
		dialog.setTitle(this.getString(R.string.sort_dialog_title));	
		dialog.setSingleChoiceItems(values, selectedSort,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						selectedSort = whichButton;
					}
				});
		dialog.setNegativeButton(TaskListActivity.this.getString(R.string.sort_by_reverse),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int whichButton) {
						String sortItem = values[selectedSort];
						Editor editor = sp.edit();
						editor.putString(SORT_ITEM, sortItem);
						editor.putLong(SORT_BY, SORT_BY_RESERVES);
						editor.commit();
						findViewById(R.id.task_list_loading).setVisibility(View.VISIBLE);
				        findViewById(R.id.task_list_view).setVisibility(View.GONE);
						initPager(sView,sPosition);
					}
				});	
		dialog.setPositiveButton(TaskListActivity.this.getString(R.string.sort_by_normal),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int whichButton) {
						String sortItem = values[selectedSort];
						Editor editor = sp.edit();
						editor.putString(SORT_ITEM, sortItem);
						editor.putLong(SORT_BY, SORT_BY_NORMAL);
						editor.commit();
						findViewById(R.id.task_list_loading).setVisibility(View.VISIBLE);
				        findViewById(R.id.task_list_view).setVisibility(View.GONE);
						initPager(sView,sPosition);
					}
				});	
		dialog.show();
	}
	
	public class TabRefreshTask extends AsyncTask<Integer, Integer, Boolean>{
		@Override
		protected Boolean doInBackground(Integer... params) {
			adapter = TaskTabAdapterFactory.getTabAdapter(TaskListActivity.this, sView);
			Message message = new Message(); 
			Bundle data = new Bundle();
			data.putInt("position", params[0].intValue());
			message.setData(data);
			tabRefreshHandler.sendMessage(message);
			return true;
		}
	}
	
	private Handler tabRefreshHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
        	int position = msg.getData().getInt("position");
        	pager.setAdapter(adapter); 
            indicator.setViewPager(pager); 
            adapter.notifyDataSetChanged(); 
            indicator.setCurrentItem(position);
            indicator.notifyDataSetChanged();
            findViewById(R.id.task_list_loading).setVisibility(View.GONE);
            findViewById(R.id.task_list_view).setVisibility(View.VISIBLE);
        }
    };
}
